package datasource

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

type LoginReq struct {
	ConditionCode string `json:"condition_code"`
	ConnectorId string `json:"connector_id"`
	TenantId string `json:"tenant_id"`
	DeviceType string `json:"device_type"`
}

type LoginRsp struct {
	Token string
}

var GLoginRsp LoginRsp

func CreateLoginBody() []byte {
	req := LoginReq{
		"12-2-192.168.88.88",
		"2",
		"12",
		"connector",
	}
	msg, err := json.Marshal(req)
	if err != nil {
		fmt.Printf("[login] create body failed : ", err)
		return nil
	}
	return msg
}

func PointLogin() bool {
	if GPointFactory.config.PointStatusUrl == "" || GPointFactory.config.PointClient == nil {
		fmt.Printf("[point] [login] report failed invalid args\n")
		return false
	}
	fmt.Printf("[point] [login] url : %s\n", GPointFactory.config.PointStatusUrl)
	msg := CreateLoginBody()
	fmt.Printf("[point] [login] report msg : %s\n", string(msg))
	bodyBuf := bytes.NewBuffer(msg)
	req, err := http.NewRequest(HttpPost, GPointFactory.config.PointLoginUrl, bodyBuf)
	if err != nil {
		fmt.Printf("[point] [login] new report failed : %v\n", err)
		return false
	}
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	rsp, err := GPointFactory.config.PointClient.Do(req)
	if err != nil {
		fmt.Printf("[point] [login] send report failed : %v\n", err)
		return false
	}
	defer rsp.Body.Close()
	if rsp == nil {
		return false
	}

	fmt.Println("rsp code   : ", rsp.StatusCode)
	rspBytes, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		fmt.Printf("[point] [login] get rsp failed : %v\n", err)
		return false
	}
	fmt.Printf("[point] [login] get rsp : %s\n", string(rspBytes))
	loginRsp := LoginRsp{}
	err = json.Unmarshal(rspBytes, &loginRsp)
	if err != nil {
		fmt.Printf("[point] [login] parse rsp failed : %v\n", err)
		return false
	}
	// 设置token
	GLoginRsp.Token = loginRsp.Token
	return true
}


